import 'package:get/get.dart';
import 'package:flutter/material.dart';
import 'package:pass_log/app/data/services/theme_service.dart';

class HomeAppBarController extends GetxController {
  var isSearching = false;
  final TextEditingController searchController = TextEditingController();

  void toggleSearch() {
    isSearching = !isSearching;
    if (!isSearching) searchController.clear();
    update();
  }
}

class HomeAppBar extends StatelessWidget implements PreferredSizeWidget {
  final Widget title;
  final void Function(bool) onToggle;
  final void Function(String) onSearch;
  const HomeAppBar({
    super.key,
    this.title = const Text("HomeAppBar"),
    this.onToggle = _defaultOnToggle,
    this.onSearch = _defaultOnSearch,
  });

  // 默认的空回调函数
  static void _defaultOnToggle(bool isSearching) {}
  static void _defaultOnSearch(String query) {}

  @override
  Widget build(BuildContext context) {
    return GetBuilder<HomeAppBarController>(
      init: HomeAppBarController(),
      builder: (ctr) => AppBar(
        title: ctr.isSearching
            ? TextField(
                controller: ctr.searchController,
                autofocus: true,
                style: TextStyle(color: ThemeService.to.curColorScheme.onPrimary),
                cursorColor: ThemeService.to.curColorScheme.onPrimary,
                decoration: InputDecoration(
                  hintText: "请输入关键字",
                  hintStyle: TextStyle(color: ThemeService.to.curColorScheme.onPrimary),
                  border: InputBorder.none,
                ),
                onChanged: (query) {
                  // 在这里处理搜索逻辑
                  onSearch(query);
                },
              )
            : title,
        centerTitle: true,
        // leading: IconButton(
        //   icon: const Icon(Icons.settings),
        //   onPressed: () => Scaffold.of(context).openDrawer(),
        // ),
        actions: [
          IconButton(
            icon: Icon(ctr.isSearching ? Icons.close : Icons.search),
            onPressed: () {
              // 在这里处理搜索框转换的逻辑
              ctr.toggleSearch();
              onToggle(ctr.isSearching);
            },
          ),
        ],
      ),
    );
  }

  @override
  Size get preferredSize => const Size.fromHeight(kToolbarHeight);
}
